package com.goldgov.branchCircle.web;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.gtiles.components.securityworkbench.bean.SwbAuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.goldgov.authorityInfo.service.AuthorityInfoInit;
import com.goldgov.branchCircle.service.AttentionService;
import com.goldgov.branchCircle.service.BranchCircle;
import com.goldgov.branchCircle.service.BranchCircleQuery;
import com.goldgov.branchCircle.service.BranchCircleService;
import com.goldgov.branchCircle.service.Message;
import com.goldgov.branchCircle.service.MessageService;
import com.goldgov.branchCircle.service.ReplyMessage;
import com.goldgov.branchCircle.service.ReplyMessageService;
import com.goldgov.branchCircle.service.ThumbUp;
import com.goldgov.branchCircle.service.ThumbUpService;
import com.goldgov.kcloud.core.json.JsonObject;
import com.goldgov.kcloud.core.json.JsonQueryObject;
import com.goldgov.kcloud.core.json.JsonSuccessObject;
import com.goldgov.login.web.model.LoginAuthUser;
import com.goldgov.utils.DateUtil;
import com.goldgov.utils.UrlUtil;
import com.goldgov.utils.excelexport.ExcelTempletExport;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/** 
 * @ClassName: BranchCircleController 
 * @Description: TODO
 * @author MaN
 * @date 2018年6月19日 
 */

@RestController
@RequestMapping("/workbench/branchCircle")
@Api("支部圈接口")
public class BranchCircleController {

	@Autowired
	private BranchCircleService branchCircleService;
	
	@Autowired
	private ThumbUpService thumbUpService;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private ReplyMessageService replyMessageService;
	
	@Autowired
	private AttentionService attentionService;
	
	/**
	 * 预新增
	 * @param obj
	 * @param request
	 * @return
	 */
	
	@GetMapping("/preAddBranchCircle")
	@ApiOperation(value = "预新增支部圈", notes ="查询返回支部圈ID")
	public JsonSuccessObject<BranchCircle> preAddBranchCircle(BranchCircle obj,HttpServletRequest request){
		obj = branchCircleService.getBranchID();
		JsonSuccessObject<BranchCircle> returnResult = new JsonSuccessObject<BranchCircle>(obj);
		return returnResult;
	}
	
	@PostMapping
	@ApiOperation(value = "新增支部圈", notes ="")
	public JsonObject<Object> addBranchCircle(BranchCircle obj,HttpServletRequest request){
		SwbAuthUser u=LoginAuthUser.getUserByAdmin(request);
		obj.setUserID(u.getEntityID());//发布人id
		obj.setStatus(BranchCircleQuery.ACTIVESTATE_YES);
		obj.setPublishDate(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
		branchCircleService.addBranchCircle(obj);
		return JsonSuccessObject.SUCCESS;
	}
	
	@RequestMapping("/listBranchCircleByAdmin")
	@ApiOperation(value = "支部圈列表", notes ="")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchOrgName", value = "支部名称", paramType = "query"),
		 @ApiImplicitParam(name = "searchBeginAttention", value = "开始关注度", paramType = "query"),
		 @ApiImplicitParam(name = "searchEndAttention", value = "结束关注度", paramType = "query"),
		 @ApiImplicitParam(name = "searchTreePath", value = "查询标识", paramType = "query"),
		 @ApiImplicitParam(name = "searchChilderOrg", value = "是否包含下级单位", paramType = "query"),
		 @ApiImplicitParam(name = "searchYear", value = "年度", paramType = "query")})
	public JsonQueryObject<BranchCircle> listBranchCircleByAdmin(@ApiIgnore BranchCircleQuery query,HttpServletRequest request){
//		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);
//		query.setSearchScopeCode(u);
		if (query.getSearchYear() != null && !"".equals(query.getSearchYear())) {
			query.setSearchYear(String.valueOf(DateUtil.getYear(new Date())));
		}
		List<BranchCircle> list=branchCircleService.getBranchCircleListByAdmin(query);
		if(null!=list && list.size()>0) {
			for(BranchCircle branch:list) {
//				String userName=branchCircleService.getDutyByID(branch.getOrgID());
				if(null!=branch.getHeadPhotoUrl() && !"".equals(branch.getHeadPhotoUrl())) {
					branch.setHeadPhotoUrl(UrlUtil.ATTACHEMEMENT_URL + branch.getHeadPhotoUrl());  
				}else {
					branch.setHeadPhotoUrl("/static/image/manner-image/default-headPhoto.png");
				}
//				branch.setUserName(userName);
			}
		}
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	
	@PostMapping("/updateThumbUp")
	@ApiOperation(value = "点赞/取消点赞", notes ="")
	public JsonObject<Object> saveThumbUp(@ApiParam(value = "branchID", required = true) @RequestParam("branchID") String branchID,HttpServletRequest request){
		ThumbUp up=new ThumbUp();
		LoginAuthUser u=LoginAuthUser.getUser(request);
		up.setUserID(u.getEntityID());
		up.setUserName(u.getUserName());
		up.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		up.setBranchID(branchID);
		thumbUpService.saveThumbUp(up);
		return JsonSuccessObject.SUCCESS;
	}
	
	@PostMapping("/addMessage")
	@ApiOperation(value = "新增留言", notes ="")
	public JsonObject<Object> addMessage(Message obj,HttpServletRequest request){
		LoginAuthUser u=LoginAuthUser.getUser(request);
		obj.setUserID(u.getEntityID());//留言人id
		obj.setUserName(u.getUserName());//留言人姓名
		obj.setStatus(BranchCircleQuery.ACTIVESTATE_YES);
		obj.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		messageService.addMessage(obj);
		return JsonSuccessObject.SUCCESS;
	}
	
	@PostMapping("/replyMessage")
	@ApiOperation(value = "回复留言", notes ="")
	public JsonObject<Object> addReplyMessage(ReplyMessage obj,HttpServletRequest request){
		LoginAuthUser u=LoginAuthUser.getUser(request);
		obj.setReplyUserID(u.getEntityID());//回复留言人id
		obj.setReplyUserName(u.getUserName());//回复留言人姓名
		obj.setStatus(BranchCircleQuery.ACTIVESTATE_YES);
		obj.setReplyDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		replyMessageService.addReplyMessage(obj);
		return JsonSuccessObject.SUCCESS;
	}
	
	
	
	@GetMapping("/replyExport")
	@ApiOperation(value = "支部圈情况统计信息", notes = "支部圈情况统计信息")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchOrgName", value = "支部名称", paramType = "query"),
		 @ApiImplicitParam(name = "searchBeginAttention", value = "开始关注度", paramType = "query"),
		 @ApiImplicitParam(name = "searchEndAttention", value = "结束关注度", paramType = "query"),
		 @ApiImplicitParam(name = "searchYear", value = "年度", paramType = "query")})
	public void replyExport(@ApiIgnore BranchCircleQuery query,HttpServletRequest request,HttpServletResponse response) throws Exception {
		query.setPageSize(-1);
		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);
		query.setSearchScopeCode(u);
		ExcelTempletExport.downloadExcel("/template/templateExamStatistic.xlsx",
				branchCircleService.getBranchCircleListByAdmin(query), "支部圈情况统计信息", response);
	}
	@GetMapping("/articleExport")
	@ApiOperation(value = "发表文章总数统计", notes = "发表文章总数统计")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchOrgID", value = "支部id", paramType = "query")})
	public void articleExport(@ApiIgnore BranchCircleQuery query,HttpServletRequest request,HttpServletResponse response) throws Exception {
		query.setPageSize(10);
		String year=DateUtil.getYear(new Date())+"";
		query.setSearchYear(year);
		ExcelTempletExport.downloadExcel("/template/templateArticleStatistic.xlsx",
				branchCircleService.countBranchCircleByID(query), "发表文章总数统计信息", response);
	}
	@RequestMapping("/countBranchCircle")
	@ApiOperation(value = "个人文章发表情况统计", notes = "个人文章发表情况统计")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchOrgID", value = "支部id", paramType = "query")})
	public JsonQueryObject<BranchCircle> countBranchCircle(@ApiIgnore BranchCircleQuery query,HttpServletRequest request,HttpServletResponse response) throws Exception {
		if (query.getSearchYear() != null && !"".equals(query.getSearchYear())) {
			query.setSearchYear(String.valueOf(DateUtil.getYear(new Date())));
		}
		List<BranchCircle> list=branchCircleService.countBranchCircleByID(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	
	@RequestMapping("/fileHelpDoc")
	  public void fileHelpDoc(HttpServletRequest request, HttpServletResponse response) throws IOException {
          String fullPath = File.separator+"template"+File.separator;
          String fileName = "宁夏党员教育综合管理平台使用手册.docx";
          // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
          response.setContentType("multipart/form-data");
          // 2.设置文件头：最后一个参数是设置下载文件名
          response.setHeader("Content-Disposition", "attachment;fileName="+ java.net.URLEncoder.encode(fileName, "UTF-8"));
          // 通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
          // File file = new File(fullPath + fileName);//返回读取指定资源的输入流
          InputStream is = this.getClass().getResourceAsStream(fullPath + fileName);
          try {
              // 3.通过response获取ServletOutputStream对象(out)
              IOUtils.copy(is, response.getOutputStream());
          } catch (IOException e) {
              throw e;
          } finally {
              if(is!=null) {
                  is.close();  
              }
             
          }
      }
	@GetMapping("/countBranchCircleByHour")
	@ApiOperation(value = "按小时统计文章发表情况", notes = "按小时统计文章发表情况")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchPublishDate", value = "发布时间", paramType = "query")})
	public JsonQueryObject<BranchCircle> countBranchCircleByHour(@ApiIgnore BranchCircleQuery query,HttpServletRequest request,HttpServletResponse response) throws Exception {
		LoginAuthUser u=LoginAuthUser.getUser(request);
		query.setSearchUserID(u.getEntityID());
		List<BranchCircle> list=branchCircleService.countBranchCircleByHour(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	
	
	
}
